package com.darren.befriend;

import java.lang.reflect.Field;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.darren.befriend.constants.Constant;
import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.MySharedPreferences;
import com.darren.befriend.utilities.Utilities;
import com.darren.befriend.views.MyCustomDialog;
import com.darren.befriend.views.MyCustomDialog.OnNegativeButtonClick;
import com.darren.befriend.views.MyCustomDialog.OnPositiveButtonClick;
import com.darren.befriend.views.MyProgressDialog;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

@SuppressLint("InflateParams")
public class SignUpActivity extends BaseActivity {
	private EditText mGenderTxt;
	private EditText mUsernamext;
	private EditText mEmailTxt;
	private EditText mPasswordTxt;
	private EditText mAgeTxt;
	private int mAge;
	private ImageView mCreateAcc;
	private NumberPicker mAgepicker;
	private Dialog mAgeDialog;
	private final int MIN_AGE = 18;
	private final int MAX_AGE = 64;
	private ParseUser mUser;
	private MyCustomDialog mErrorDialog;
	private MyProgressDialog mDialog;

	@Override
	protected int addContent() {

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		return R.layout.layout_sign_up;
	}

	@Override
	protected void initView() {
		super.initView();

		mGenderTxt = (EditText) findViewById(R.id.gender_txt);
		mUsernamext = (EditText) findViewById(R.id.username_txt);
		mEmailTxt = (EditText) findViewById(R.id.email_txt);
		mPasswordTxt = (EditText) findViewById(R.id.password_txt);
		mAgeTxt = (EditText) findViewById(R.id.age_txt);
		mCreateAcc = (ImageView) findViewById(R.id.signup_btn);

		mGenderTxt.setOnClickListener(this);
		mAgeTxt.setOnClickListener(this);
		mCreateAcc.setOnClickListener(this);

		Utilities.setFontType(this, mGenderTxt);
		Utilities.setFontType(this, mUsernamext);
		Utilities.setFontType(this, mEmailTxt);
		Utilities.setFontType(this, mPasswordTxt);
		Utilities.setFontType(this, mAgeTxt);

		findViewById(R.id.main_view).setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Utilities.hideKeyboard(SignUpActivity.this);
				return false;
			}
		});
	}

	/**
	 * show agePicker
	 */
	private void showAgePicker() {

		String years = getString(R.string.year_text);
		String[] ageStringArr = new String[MAX_AGE - MIN_AGE + 1];
		for (int i = MIN_AGE; i <= MAX_AGE; i++) {

			ageStringArr[i - MIN_AGE] = i + " " + years;
		}

		LayoutInflater dialogInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View agePickerView = dialogInflater.inflate(R.layout.layout_age_picker,
				null);
		TextView doneTxt = (TextView) agePickerView.findViewById(R.id.done_txt);
		doneTxt.setOnClickListener(this);
		mAgepicker = (NumberPicker) agePickerView.findViewById(R.id.age_picker);
		mAgepicker.setMinValue(0);
		mAgepicker.setMaxValue(MAX_AGE - MIN_AGE);
		mAgepicker.setDisplayedValues(ageStringArr);
		mAgepicker
				.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
		mAgeDialog = new Dialog(SignUpActivity.this);
		mAgeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mAgeDialog.setCancelable(true);
		mAgeDialog.setContentView(agePickerView);
		mAgeDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		setNumberPickerTextColor(mAgepicker, Color.BLACK);
		mAgeDialog.show();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.gender_txt:
			final MyCustomDialog dialog = new MyCustomDialog(
					SignUpActivity.this);
			dialog.setCancelableFlag(false);
			dialog.setTitle(getString(R.string.gender_select_title));
			dialog.setMessage(getString(R.string.gender_select_message));
			dialog.setNegativeButton(getString(R.string.male),
					new OnNegativeButtonClick() {

						@Override
						public void onButtonClick(final View view) {
							mGenderTxt.setText(R.string.male);
							dialog.dismiss();
						}
					});
			dialog.setPositiveButton(getString(R.string.female),
					new OnPositiveButtonClick() {

						@Override
						public void onButtonClick(View view) {
							mGenderTxt.setText(R.string.female);
							dialog.dismiss();
						}
					});
			dialog.show();
			break;
		case R.id.age_txt:

			showAgePicker();
			break;
		case R.id.signup_btn:

			mDialog = MyProgressDialog.show(SignUpActivity.this, "", "", false,
					false);
			signUp();
			break;
		case R.id.done_txt:

			mAge = mAgepicker.getValue() + MIN_AGE;
			mAgeTxt.setText(String.valueOf(mAge));
			mAgeDialog.dismiss();
			break;
		default:
			break;
		}
	}

	/**
	 * sign up
	 */
	private void signUp() {
		if (mUsernamext.getText().toString().isEmpty()) {

			mDialog.dismiss();
			createDialog(getString(R.string.input_user_error));
			return;
		}

		if (mEmailTxt.getText().toString().isEmpty()) {

			mDialog.dismiss();
			createDialog(getString(R.string.input_email_error));
			return;
		}

		if (mPasswordTxt.getText().toString().isEmpty()) {

			mDialog.dismiss();
			createDialog(getString(R.string.input_psw_error));
			return;
		}

		if (mAgeTxt.getText().toString().isEmpty()) {

			mDialog.dismiss();
			createDialog(getString(R.string.input_age_error));
			return;
		}

		if (mGenderTxt.getText().toString().isEmpty()) {

			mDialog.dismiss();
			createDialog(getString(R.string.input_gender_error));
			return;
		}

		mUser = new ParseUser();
		mUser.setUsername(mUsernamext.getText().toString());
		mUser.setPassword(mPasswordTxt.getText().toString());
		mUser.setEmail(mEmailTxt.getText().toString());
		mUser.signUpInBackground(new SignUpCallback() {

			@Override
			public void done(ParseException ex) {
				if (ex == null) {
					mUser.put("fullName", mUsernamext.getText().toString()
							+ "_local");
					mUser.put("Friends", new ArrayList<String>());
					mUser.put("Enemy", new ArrayList<String>());

					//
					ParseObject meInfo = new ParseObject("MeClass");
					if (mGenderTxt.getText().toString().equals("Male")) {

						meInfo.put("Gender", 0);
					} else {

						meInfo.put("Gender", 1);
					}

					meInfo.put("MoneyToBurn", 500);
					meInfo.put("MyAge", mAge);
					meInfo.put("Nationality", 0);
					meInfo.put("Religion", 0);
					meInfo.put("Personality", 0);
					meInfo.put("Children", 0);
					meInfo.put("Intelligence", 1);
					meInfo.put("University", 0);
					meInfo.put("Employer", "");
					meInfo.put("About", "");
					meInfo.put("Parent", mUser.getUsername());
					ArrayList<Boolean> selectionArray = new ArrayList<Boolean>();
					for (int i = 0; i < 9; i++) {

						selectionArray.add(i, false);
					}

					meInfo.put("Hobby", selectionArray);
					mUser.put("MeInfo", meInfo);

					// create Filter Info
					ParseObject filter = new ParseObject("FilterClass");
					filter.put("Men", true);
					filter.put("Women", true);
					filter.put("Within", 25);
					filter.put("StartAge", 23);
					filter.put("EndAge", 38);
					filter.put("StartMoney", 200);
					filter.put("EndMoney", 600);
					filter.put("Parent", mUser.getUsername());
					ArrayList<Boolean> personalityArray = new ArrayList<Boolean>();
					for (int i = 0; i < 13; i++) {

						personalityArray.add(i, false);
					}

					filter.put("Personality", personalityArray);
					mUser.put("Filter", filter);
					mUser.put("Status", true);
					ParseInstallation currentInstallation = ParseInstallation
							.getCurrentInstallation();
					currentInstallation.addUnique("channels",
							"CH_" + mUser.getUsername());
					currentInstallation.saveInBackground();
					if (mGeoPoint != null) {

						mUser.put("Position", mGeoPoint);
					}

					MySharedPreferences.setPreferences(
							MySharedPreferences.PREF_USERNAME,
							mUser.getUsername());
					MySharedPreferences.setPreferences(
							MySharedPreferences.PREF_PASSWORD, mPasswordTxt
									.getText().toString());
					mParseUser = mUser;
					try {

						mUser.saveInBackground();

					} catch (Exception e) {

						e.printStackTrace();
					}

					mDialog.dismiss();
					Intent newintent1 = new Intent(SignUpActivity.this,
							UserSettingInitialActivity.class);
					MySharedPreferences.setPreferences(
							Constant.IS_FROM_SIGNUP_SCREEN, true);
					startActivity(newintent1);
					finish();
				} else {

					mDialog.dismiss();
					createDialog(ex.getMessage());
				}
			}
		});
	}

	/**
	 * create dialog
	 */
	private void createDialog(String message) {
		mErrorDialog = new MyCustomDialog(SignUpActivity.this);
		mErrorDialog.setTitle(getString(R.string.error_label));
		mErrorDialog.setMessage(message);
		mErrorDialog.setNegativeButton(getString(R.string.ok_label),
				new OnNegativeButtonClick() {

					@Override
					public void onButtonClick(final View view) {

						mErrorDialog.dismiss();
					}
				});

		mErrorDialog.show();
	}

	public void setNumberPickerTextColor(NumberPicker numberPicker, int color) {

		final int count = numberPicker.getChildCount();
		for (int i = 0; i < count; i++) {

			View child = numberPicker.getChildAt(i);
			if (child instanceof EditText) {

				try {

					Field selectorWheelPaintField = numberPicker.getClass()
							.getDeclaredField("mSelectorWheelPaint");
					selectorWheelPaintField.setAccessible(true);
					((Paint) selectorWheelPaintField.get(numberPicker))
							.setColor(color);
					((EditText) child).setTextColor(color);
					numberPicker.invalidate();
				} catch (Exception e) {

					LogUtil.e("setNumberPickerTextColor()", e.getMessage());
				}
			}
		}
	}
}
